package net.ib.mtalk.ui.start;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.ib.mntalk.protocol.Common.AccountAuthToken;
import net.ib.mntalk.protocol.Common.AccountToken;
import net.ib.mntalk.protocol.Session.AcquireAccountAuthTokenRes;
import net.ib.mtalk.R;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.constant.MTalkIntent;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.global.PhoneUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 가입화면중 번호인증 Activity
 * 전화번호나 앰엔톡ID로 인증가능
 * @author urunimi
 *
 */
public class AccountPhoneActivity extends Activity {

	
	final int REQUEST_CODE_COUNTRY = 0x10;
	final int REQUEST_CODE_COUNTRY_NO_INPUT = 0x00;
	
	final String DEFAULT_COUNTRY = "South Korea";
	final int DEFAULT_COUNTRY_CODE = 82;
	String selectedCountryCode;
	String selectedCountryName = DEFAULT_COUNTRY;
	
	Button buttonCountry;
	EditText editCountryCode;
	EditText editPhoneNumber;
	Map<CharSequence, CharSequence> countryMap = new HashMap<CharSequence, CharSequence>();
	private String country_code = "";
	private String tel_num = "";
	
	protected Context mContext;
	private AccountAuthToken mAccountAuthToken;
	private AccountPhoneController mUiController;
	
	private ProgressDialog mProgressDialog;
	
	public boolean mExistRedirect = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_account_phone);
		
		mContext = this;
		mUiController = new AccountPhoneController(mContext, mHandler);
		mExistRedirect = getIntent().getBooleanExtra("redirect", false);
		
		mProgressDialog = new ProgressDialog(mContext);
		mProgressDialog.setMessage(getString(R.string.waiting));
		mProgressDialog.setCancelable(false);
		
		selectedCountryCode = "+" + DEFAULT_COUNTRY_CODE;
		buttonCountry = (Button) findViewById(R.id.buttonCountry);
		editCountryCode = (EditText) findViewById(R.id.editCountryCode);
		editPhoneNumber = (EditText) findViewById(R.id.editPhoneNumber);
		
		CharSequence[] country = getResources().getTextArray(R.array.country);
		CharSequence[] countryCode = getResources().getTextArray(R.array.country_code);
		
		editCountryCode.setText(selectedCountryCode);
		buttonCountry.setText(DEFAULT_COUNTRY);
		
		for(int i=0; i < country.length; ++i) {
			countryMap.put(country[i], countryCode[i]);
		}
		
		
	}
	
	public void onOkClick(View view) {
		if(editPhoneNumber.getText().length() > 0) {
			if(isExistNumber())
			{
				new AlertDialog.Builder(mContext).setMessage(getString(R.string.setting_profile_add_phone_exist_msg))
				.setNegativeButton(R.string.done, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
				return;
			}
			showDialog(REQUEST_CODE_COUNTRY);
		} else {
			showDialog(REQUEST_CODE_COUNTRY_NO_INPUT);
		}
	}
	
	private boolean isExistNumber()
	{
		ArrayList<String> codes = getIntent().getStringArrayListExtra("code");
		ArrayList<String> numbers = getIntent().getStringArrayListExtra("number");
		
		if(codes == null || numbers == null)
			return false;
		
		String myCode = selectedCountryCode;
		String myNumber = editPhoneNumber.getText().toString();
		
		if(codes.contains(myCode) && numbers.contains(myNumber))
			return true;
		
		return false;
	}
	
	public void onCountryClick(View view) {
		startActivityForResult(new Intent(this, CountryActivity.class), REQUEST_CODE_COUNTRY);
	}

	public void onDestroy()
	{
		super.onDestroy();
		if(mProgressDialog != null)
		{
			mProgressDialog.hide();
			mProgressDialog.dismiss();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode != RESULT_OK) return;
		switch(requestCode) {
		case REQUEST_CODE_COUNTRY:
			final Bundle bundle = data.getExtras();
			getIntent().putExtras(bundle);
			selectedCountryName = bundle.getString(MTalkIntent.KEY_COUNTRY_NAME);
			selectedCountryCode = "+" + countryMap.get(selectedCountryName).toString();
			editCountryCode.setText(String.valueOf(selectedCountryCode));	//0412 ljw : String값으로 변환
			buttonCountry.setText(selectedCountryName);
			break;
		}
	}
	
	Dialog confirmDialog = null;
	
	@Override
	protected Dialog onCreateDialog(int id) {		//0412 ljw : 전반적으로 수정
		TextView confirmDialogTextView = new TextView(this);
		confirmDialogTextView.setGravity(Gravity.CENTER);
		confirmDialogTextView.setTextColor(Color.WHITE);
		
		switch(id) {
		case REQUEST_CODE_COUNTRY:
			final String cellNumber = editPhoneNumber.getText().toString().trim();
			//final int trimmedCellNumber = Integer.parseInt(cellNumber);
			StringBuilder sb = new StringBuilder();
			sb.append("<p><h4>").append(selectedCountryName).append("  (").append(selectedCountryCode).append(")</h4></p>");
			sb.append("<p><strong><h1>").append(cellNumber).append("</h1></strong></p>");
			sb.append(getString(R.string.join_confirm_msg));
			/*String text = 
				"<p><h4>" + selectedCountryName + "  (" + selectedCountryCode + ")</h4></p>"
				+"<p><strong><h1>"	+ cellNumber + "</h1></strong></p>"
				+ "입력하신 전화번호와 사용중인 국가가 맞습니까?";*/
			
			confirmDialogTextView.setText(Html.fromHtml(sb.toString()));
			
			confirmDialog = new AlertDialog.Builder(this)
							.setTitle(getString(R.string.join_phone_number_verification))
							.setView(confirmDialogTextView)
							.setPositiveButton(android.R.string.yes, new OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									/*TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
									String myNumber = mTelephonyMgr.getLine1Number();
									if(cellNumber.equals(myNumber))*/
									if(PhoneUtils.compareUsimNumber(mContext, cellNumber, selectedCountryCode))
									{
										mUiController.acquireAccountAuthToServer(selectedCountryCode, cellNumber);
										mProgressDialog.show();
									}
									else
									{
										Intent i = new Intent(AccountPhoneActivity.this, AuthenticationActivity.class);
										i.putExtra(MTalkIntent.KEY_COUNTRY_CODE, selectedCountryCode);
										i.putExtra(MTalkIntent.KEY_CELL_NUMBER, cellNumber);
										i.putExtra("redirect", mExistRedirect);
										finish();
										startActivity(i);
									}
								}
							})
							.setNegativeButton(android.R.string.no, new OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									removeDialog(REQUEST_CODE_COUNTRY);
								}
							}).create();
			country_code = selectedCountryCode;
			tel_num = cellNumber;
			return confirmDialog;
		case REQUEST_CODE_COUNTRY_NO_INPUT:
			confirmDialogTextView.setTextSize(15);
			confirmDialogTextView.setText(getString(R.string.join_enter_phone_number_msg));
			confirmDialog = new AlertDialog.Builder(this)
			.setView(confirmDialogTextView)
			.setNegativeButton(getString(R.string.ok), new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(REQUEST_CODE_COUNTRY_NO_INPUT);
				}
			}).create();
			return confirmDialog;
		}
		
		return super.onCreateDialog(id);
	}
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
				case HandlerMsgConst.HANDLER_UNKNOWN_ERROR :
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR!", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_AUTH_SUCCESS :
					GlobalPreferences.setMSISDN("+" + country_code + tel_num);
					AcquireAccountAuthTokenRes res = (AcquireAccountAuthTokenRes) msg.obj;
					mAccountAuthToken = res.getAccountAuthToken();
					mUiController.acquireAccountToServer(mAccountAuthToken, new String(res.getAuthCodeEnc().toByteArray()));
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_AUTH_SUCCESS", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_AUTH_FAIL :
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_AUTH_FAIL", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_SUCCESS:
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_SUCCESS", Toast.LENGTH_SHORT).show();
					mUiController.setUserAccount((AccountToken)msg.obj);
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_FAIL:
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_FAIL", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_REGISTER_ACCOUNT_SUCCESS:
					Toast.makeText(mContext, "HANDLER_REGISTER_ACCOUNT_SUCCESS", Toast.LENGTH_SHORT).show();
					setResult(RESULT_OK, getIntent());
					finish();
					break;
				case HandlerMsgConst.HANDLER_REGISTER_ACCOUNT_FAIL:
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_REGISTER_ACCOUNT_FAIL", Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		}
	};
}
